package org.catpay.modules.app.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.catpay.common.exception.RRException;
import org.catpay.common.utils.PageUtils;
import org.catpay.common.utils.Query;
import org.catpay.modules.app.dao.UserDao;
import org.catpay.modules.app.entity.UserAddressEntity;
import org.catpay.modules.app.entity.UserEntity;
import org.catpay.modules.app.service.UserService;
import org.catpay.modules.app.utils.CacheLocal;
import org.catpay.modules.app.vo.PartnerInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
	@Value("${AccessKeyId}")
	private String AccessKeyId;
	@Value("${AccessKeySecret}")
	private String AccessKeySecret;
	@Value("${SignName}")
	private String SignName;
	@Autowired
	private QiniuyunServiceImpl qiniuyunService;

	@Override
	public UserEntity queryByMobile(String mobile) {
		UserEntity userEntity = new UserEntity();
		userEntity.setPhone(mobile);
		return baseMapper.selectOne(userEntity);
	}

	@Override
	public UserEntity login(String phone, String password) {
		UserEntity user = queryByMobile(phone);
		if (user == null) {
			throw new RRException("手机号或密码错误");
		}
		// 密码错误
		if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
			throw new RRException("手机号或密码错误");
		}

		return user;
	}

	@Override
	public void sendSms(String tel) {
		String templateCode = "SMS_171090985";
		Map<String, Object> param = new HashMap<>();
		String code = RandomUtil.randomNumbers(4);
		param.put("code", code);
		try {
			CacheLocal.setPhoneCode(tel, code);
			sendSms(tel, param, templateCode);
		} catch (ClientException e) {
			throw new RRException(e.getErrMsg());
		}
	}

	private void sendSms(String tel, Map<String, Object> param, String templateCode) throws ClientException {
		// 设置超时时间-可自行调整
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		// 初始化ascClient需要的几个参数
		final String product = "Dysmsapi";// 短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名（接口地址固定，无需修改）
		// 替换成你的AK
		final String accessKeyId = AccessKeyId;// 你的accessKeyId,参考本文档步骤2
		final String accessKeySecret = AccessKeySecret;// 你的accessKeySecret，参考本文档步骤2
		// 初始化ascClient,暂时不支持多region
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);
		// 组装请求对象
		SendSmsRequest request = new SendSmsRequest();
		// 使用post提交
		request.setMethod(MethodType.POST);
		// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
		request.setPhoneNumbers(tel);
		// 必填:短信签名-可在短信控制台中找到
		request.setSignName(SignName);
		// 必填:短信模板-可在短信控制台中找到
		request.setTemplateCode(templateCode);
		// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		request.setTemplateParam(JSON.toJSONString(param));
		// 可选-上行短信扩展码(无特殊需求用户请忽略此字段)
		// request.setSmsUpExtendCode("90997");
		// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		request.setOutId("yourOutId");
		// 请求失败这里会抛ClientException异常
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		System.out.println(JSON.toJSONString(sendSmsResponse));
		String code = sendSmsResponse.getCode();
		String message = sendSmsResponse.getMessage();
		// System.out.println(message);
		if (!"OK".equals(code)) {
			throw new RRException(message);
		}
	}

	@Override
	public List<UserEntity> getUserPartner(Long userId, String userName) {
		List<UserEntity> userEntityList = new ArrayList<>();
		// 获取父伙伴
		UserEntity userEntity = baseMapper.selectById(userId);
		Long fatherid = userEntity.getFatherId();
		if (null == fatherid) {
			userEntityList.add(null);
		} else {
			userEntityList.add(baseMapper.selectById(fatherid));
		}

		// 获取子伙伴
		List<UserEntity> childUserEntityList = baseMapper
				.selectList(new EntityWrapper<UserEntity>().eq("father_id", userId)
						.like(StrUtil.isNotBlank(userName), "nick_name", userName).orderBy("create_time", false));
		for (UserEntity childUserEntity : childUserEntityList) {
			userEntityList.add(childUserEntity);
		}
		return userEntityList;
	}

	@Override
	public UserEntity getUser(Long userId) {
		return new UserEntity().selectById(userId);
	}

	@Override
	public void updatePassword(String phone, String password) {
		baseMapper.updatePassword(phone, DigestUtils.sha256Hex(password));
	}

	@Override
	public UserAddressEntity setAddress(UserEntity user, String name, String phone, String province, String city,
			String area, String address, String type) {
		UserAddressEntity userAddressEntity = new UserAddressEntity();
		userAddressEntity.setUserId(user.getId());
		userAddressEntity.setName(name);
		userAddressEntity.setPhone(phone);
		userAddressEntity.setProvince(province);
		userAddressEntity.setCity(city);
		userAddressEntity.setArea(area);
		userAddressEntity.setAddress(address);
		userAddressEntity.setIsDefault(type);
		// userAddressEntity.setLabel();
		userAddressEntity.setCreateTime(new Date());
		baseMapper.setAddress(userAddressEntity);
		return userAddressEntity;
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String phone = MapUtils.getString(params, "phone");
		Page<UserEntity> page = this.selectPage(new Query<UserEntity>(params).getPage(), new EntityWrapper<UserEntity>()
				.eq(StringUtils.isNotBlank(phone), "phone", phone).orderDesc(Arrays.asList("create_time")));

		return new PageUtils(page);
	}

	@Override
	public List<UserAddressEntity> getAddress(Long userId) {
		return baseMapper.getAddress(userId);
	}

	@Override
	public PartnerInfo getPartner(Long userId, String dateTime) {
		List<UserEntity> l = baseMapper.selectList(new EntityWrapper<UserEntity>().eq("father_id", userId)
				.ge("create_time", DateUtil.parse(dateTime + "-01 00:00:00"))
				.le("create_time", dateTime + "-30 23:59:59"));
		BigDecimal bd = new BigDecimal(0);
		Integer sum0Partner = 0;
		Integer sum1Partner = 0;
		Integer sum2Partner = 0;
		Integer sum3Partner = 0;
		for (UserEntity u : l) {
			bd.add(u.getProfitBalance());
			if (u.getLevel() == 0) {
				sum0Partner++;
			}
			if (u.getLevel() == 1) {
				sum1Partner++;
			}
			if (u.getLevel() == 2) {
				sum2Partner++;
			}
			if (u.getLevel() == 3) {
				sum3Partner++;
			}
		}

		PartnerInfo partnerInfo = new PartnerInfo(); // baseMapper.getPartner(userId);
		partnerInfo.setSumGoods(100);
		partnerInfo.setSum0Partner(sum0Partner);
		partnerInfo.setSum1Partner(sum1Partner);
		partnerInfo.setSum2Partner(sum2Partner);
		partnerInfo.setSum3Partner(sum3Partner);
		partnerInfo.setSumAmount(bd);
		return partnerInfo;
	}

	@Override
	public PartnerInfo getPartner(Long userId) {
		List<UserEntity> l = baseMapper.selectList(new EntityWrapper<UserEntity>().eq("father_id", userId));
		BigDecimal bd = new BigDecimal(0);
		Integer sum0Partner = 0;
		Integer sum1Partner = 0;
		Integer sum2Partner = 0;
		Integer sum3Partner = 0;
		for (UserEntity u : l) {
			bd.add(u.getProfitBalance());
			if (u.getLevel() == 0) {
				sum0Partner++;
			}
			if (u.getLevel() == 1) {
				sum1Partner++;
			}
			if (u.getLevel() == 2) {
				sum2Partner++;
			}
			if (u.getLevel() == 3) {
				sum3Partner++;
			}
		}

		PartnerInfo partnerInfo = new PartnerInfo(); // baseMapper.getPartner(userId);
		partnerInfo.setSumGoods(100);
		partnerInfo.setSum0Partner(sum0Partner);
		partnerInfo.setSum1Partner(sum1Partner);
		partnerInfo.setSum2Partner(sum2Partner);
		partnerInfo.setSum3Partner(sum3Partner);
		partnerInfo.setSumAmount(bd);
		return partnerInfo;
	}

	@Override
	public void setDefaultAddress(UserEntity user, Long addId) {
		baseMapper.setAddressUnDe(user.getId());

		UserAddressEntity userAddressEntity = baseMapper.getAddressById(addId);
		baseMapper.setDefaultAddress(userAddressEntity);
	}

	@Override
	public UserAddressEntity updateAddress(UserEntity user, Long addId, String name, String phone, String province,
			String city, String area, String address) {
		UserAddressEntity userAddressEntity = baseMapper.getAddressById(addId);
		userAddressEntity.setUserId(user.getId());
		userAddressEntity.setName(name);
		userAddressEntity.setPhone(phone);
		userAddressEntity.setProvince(province);
		userAddressEntity.setCity(city);
		userAddressEntity.setArea(area);
		userAddressEntity.setAddress(address);

		userAddressEntity.setCreateTime(new Date());
		baseMapper.updateAddress(userAddressEntity);
		return userAddressEntity;
	}

	@Override
	public List<Long> getSharePage() {
		return baseMapper.getSharePage();
	}

	@Override
	public UserEntity updateUserInfo(long uid, String headImage, String nickName) {
		UserEntity user = baseMapper.selectById(uid);
		if (nickName != null)
			user.setNickName(nickName);
		if (headImage != null)
			user.setHeadImage(headImage);
		baseMapper.updateById(user);
		return user;
	}

	@Override
	public String updateUserHeadImage(long uid, MultipartFile headImage) {

		try {
			return qiniuyunService.convertImageUrl(qiniuyunService.uploadMultipartFile(headImage, "JPG"));
		} catch (IOException e) {
			throw new RRException("上传头像失败");
		}
	}

}
